/*
 * IBM Corporation.
 * Copyright (c) 2014 All Rights Reserved.
 */

package com.xxl.job.core.registry.impl;

import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response.Status.Family;

import org.apache.wink.client.ClientResponse;
import org.apache.wink.client.Resource;
import org.apache.wink.client.RestClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xxl.job.core.biz.model.JobRegistVO;
import com.xxl.job.core.registry.RegistHelper;

/**
 * 类作用：
 * @author Johnny@cn.ibm.com
 * 使用说明：
 */
public class RestRegistHelper implements RegistHelper {
	private final Logger logger = LoggerFactory.getLogger(RestRegistHelper.class);
	private String registryServerUrl;
	/* (non-Javadoc)
	 * @see com.xxl.job.core.registry.RegistHelper#registry(java.lang.String, java.lang.String, java.lang.String)
	 */
	@Override
	public int registry(String registGroup, String registryKey, String registryValue) {
		RestClient client = new RestClient();
		Resource res = client.resource(registryServerUrl);
		ObjectMapper om = new ObjectMapper();
		JobRegistVO jobReg = new JobRegistVO(registGroup, registryKey,registryValue);
		try {
			String json = om.writeValueAsString(jobReg);
			logger.debug("to regiter:{}", json);
			ClientResponse rst = res.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON).put(json);
			if (rst.getStatusType().getFamily() != Family.SUCCESSFUL) {
				logger.error("Error responsed from rest registry, code {}, message {}", rst.getStatusCode(), rst.getMessage());
				// throw new RuntimeException("Error code " + rst.getStatusCode() + " message " + rst.getMessage());
			}
		} catch (JsonProcessingException e) {
			logger.error("Error responsed from rest registry", e);
		}
		return 0;
	}

	public void setRegistryServerUrl(String registryServerUrl) {
		this.registryServerUrl = registryServerUrl;
	}

}
